/**
 * FileName: Message
 * Author:   powersi
 * Date:     2021/2/26 10:23
 * Description:
 */
package com.zm.demo.netty.action.common;

import com.zm.demo.netty.action.util.JsonUtil;
import io.netty.buffer.ByteBuf;
import lombok.Data;

import java.nio.charset.StandardCharsets;

/**
 * Description: 
 * Author:      powersi
 * Date:        2021/2/26 10:23
 */
@Data
public abstract class Message<T extends MessageBody> {

    private MessageHeader messageHeader;
    private T messageBody;

    public void encode(ByteBuf byteBuf){
        byteBuf.writeInt(messageHeader.getVersion());
        byteBuf.writeInt(messageHeader.getReqType());
        byteBuf.writeLong(messageHeader.getReqId());
        byteBuf.writeBytes(JsonUtil.toJson(messageBody).getBytes());
    }

    public abstract Class<T> getMessageBodyClass(int reqType);

    public void decode(ByteBuf msg){
        int version = msg.readInt();
        int reqType = msg.readInt();
        long reqId = msg.readLong();

        MessageHeader messageHeader = new MessageHeader();
        messageHeader.setReqId(reqId);
        messageHeader.setReqType(reqType);
        messageHeader.setVersion(version);
        this.messageHeader = messageHeader;

        Class<T> bodyClazz  =getMessageBodyClass(reqType);
        T body = JsonUtil.fromJson(msg.toString(StandardCharsets.UTF_8), bodyClazz);
        this.messageBody = body;
    }

}
